# -*-coding:utf-8 -*-
# author: leemon
# datetime: 2020/9/15 14:14
import requests
import json
import random


class HuaweicloudOvpn:
    def __init__(self, url, username='admin', password='admin@123'):
        self.url = url
        self.username = username
        self.password = password
        self.req = requests.session()
        self.header = {}

    def login(self):
        token_url = '%s/token' % self.url
        params = {'username': self.username, 'password': self.password}
        res = self.req.post(token_url, params)
        if res.status_code != 200:
            print(res.content)
            return False
        json_res = json.loads(res.content)
        self.header.update({'Authorization': '%s %s' % (json_res['token_type'], json_res['access_token'])})
        return True

    def useradd(self, username, password):
        status = True
        msg = ''

        useradd_params = {'username': username, 'password': password}
        res = self.req.post('%s/create' % self.url, useradd_params, headers=self.header)
        if res.status_code != 200:
            msg = res.content
            status = False

        return {'status': status, 'username': username, 'password': password, 'view_url': self.url, 'msg': msg, 'type': 'fastapi'}

    def usersearch(self, username):
        res = self.req.get('%s/user/search?username=%s' % (self.url, username), headers=self.header)
        if res.status_code == 200:
            json_res = json.loads(res.content)
            status = json_res['status']

            return status

        return False

    def get_all_users(self):
        res = self.req.get('%s/user/all' % (self.url), headers=self.header)
        if res.status_code == 200:
            json_res = json.loads(res.content)
            users = json_res['users']

            return users

        return False


if __name__ == '__main__':
    pass